﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

/// <summary>
/// 客户端数据表 的管理类
/// </summary>
/// <typeparam name="T">数据表类</typeparam>
/// <typeparam name="B">数据表管理子类</typeparam>
public abstract class DataDBMgrBase <T,B> : InstanticeBase<B> where T : DataEntityBase where B :new()
{
    /// <summary>
    /// data列表
    /// </summary>
    public List<T> Lst { get; private set; }

    /// <summary>
    /// data 字典
    /// </summary>
    public Dictionary<int, T> Dic { get; private set; }

    /// <summary>
    /// data 表的 加载路径
    /// </summary>
    protected string m_DataPath = null;

    /// <summary>
    /// 表名字
    /// </summary>
    protected abstract string DataName { get; }

    /// <summary>
    /// 构造函数
    /// </summary>
    public DataDBMgrBase()
    {
        SetDataPath();
        if (!File.Exists(m_DataPath))
        {
            Debug.LogError("data 文件不存在：" + m_DataPath);
            return;
        }
        ReadDataTable();
    }

    /// <summary>
    /// 读取表格
    /// </summary>
    private void ReadDataTable()
    {
        byte[] dataByte;
        using (FileStream fs = new FileStream(m_DataPath, FileMode.Open))
        {
            dataByte = new byte[fs.Length];
            fs.Read(dataByte, 0, dataByte.Length);
        }

        using (MMO_MemoryStream ms = new MMO_MemoryStream(dataByte))
        {
            //读取 有多少个 数据实体
            int listCount = ms.ReadInt();

            //初始化 list 长度
            Lst = new List<T>(listCount);
            //初始化 dictionary 长度
            Dic = new Dictionary<int, T>(listCount);

            T entity;
            for (int i = 0; i < listCount; i++)
            {
                entity = GetEntity(ms);

                Lst.Add(entity);
                Dic[entity.Id] = entity;
            }
        }
    }

    /// <summary>
    /// 需要 子类去实现
    /// </summary>
    /// <param name="ms"></param>
    /// <returns></returns>
    protected abstract T GetEntity(MMO_MemoryStream ms);

    /// <summary>
    /// 需要 根据自己的需求 去实现 对应的路径
    /// </summary>
    /// <param name="ms"></param>
    /// <returns></returns>
    private void SetDataPath()
    {
        m_DataPath = @"F:\ExcelToData\DataTableExample_UnityProject\Assets\DownLoad\DataTable\" + DataName;
    }
}
